package com.ruoyi.kis.controller;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult_KIS;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.kis.Vars.Constants;
import com.ruoyi.kis.annotaion.BasicAuthCheck;
import com.ruoyi.kis.domain.DispatchOrderF;
import com.ruoyi.kis.service.IKisService;
import com.ruoyi.kis.util.HttpSendWmsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Author: zhanglm
 * @CreateDate: 2025-02-28 14:24
 * @FullNameClass: com.ruoyi.kis.controller.KisFhtzController
 * @Description: 发货通知、销售出库单反馈
 * 发货通知单下发给wms，wms根据发货通知单给erp反馈销售出库单？
 */
@RestController
@RequestMapping("/kisfhtzd")
@Component("kisfhtzd")
@Api("kis接口")
public class KisFhtzController extends BaseController {



    @Autowired
    private IKisService kisService;

    private static final Logger LOGGER = LoggerFactory.getLogger(KisFhtzController.class);


    /**
     * 发货通知单
     * @return
     * ERP > WMS
     * 表名：SEOutStockSEOutStock
     */
    @ApiOperation("发货通知单")
    @RequestMapping("/fhtzd")
    public AjaxResult_KIS dispatchorder(){

        List<DispatchOrderF> dispatchOrderFList = kisService.queryDispatchOrder();
        if (dispatchOrderFList == null || dispatchOrderFList.isEmpty() || dispatchOrderFList.size() == 0){
            return AjaxResult_KIS.success("OK",null);
        }

        String s = JSONUtil.toJsonStr(dispatchOrderFList.get(0));
        LOGGER.info("发货通知单ERP >> WMS的JSON:"+s);
        try {

//            String msg = HttpUtil.post(Constants.DISPATCH_ORDER_URL,s);
            String msg = HttpSendWmsUtil.sendWms(Constants.DISPATCH_ORDER_URL,s);
//            String msg = HttpUtil.post("http://localhost:8081/kis/test",s);
            if(msg != null && StringUtils.isNotEmpty(msg)){
                JSONObject entries = JSONUtil.parseObj(msg);
                String msgcode = entries.get("msgcode").toString();
                String kisFlag;
                if (msgcode.equals(Constants.ZHIKU.MSGCODE_SUCCESS)){
                    kisFlag = Constants.ZHIKU.KISFLAG_SUCCESS;
                }else {
                    kisFlag = Constants.ZHIKU.KISFLAG_FAILURE;
                }
                int updateCount = kisService.updateKisSEOutStockFlag(dispatchOrderFList.get(0).getFInterID(),kisFlag);
                LOGGER.info("发货通知单ERP >> WMS:单据：{}更新kisFlag状态：{}更新:{}条,反馈：{}",dispatchOrderFList.get(0).getFBillNo(),kisFlag,updateCount,msg);
            }
        }catch (HttpException e){
            LOGGER.error("发货通知单" + e.getMessage());
            return AjaxResult_KIS.error("wms服务器不通！");
        }
        return AjaxResult_KIS.success();
    }
    /**
     * 销售出库单（发货通知单）
     * @return
     * WMS > ERP
     * 废弃，将下面功能放到KisXsckdController中处理了
     */
    @ApiOperation("销售出库单反馈")
    @RequestMapping("/fhtzdfeedback")
    @BasicAuthCheck
    public AjaxResult_KIS dispatchorderFeedback(@RequestBody DispatchOrderF dispatchOrderF){

//        int count = kisService.updateFhtzdFeedBack(dispatchOrderF);

        LOGGER.info(JSONUtil.parse(dispatchOrderF).toString());
//        int count = kisService.updateFhtzdFeedBack(dispatchOrderF);
        Map<String,Object> map = new HashMap<>();
        if(dispatchOrderF.getFROB().equals("1")){
            LOGGER.info("发货通知单反馈（销售出库单）给的值："+dispatchOrderF);
            map = kisService.insertXsckd(dispatchOrderF);
            LOGGER.info("发货通知单反馈（销售出库单）："+map);
        }else {
            LOGGER.info("退货通知单反馈（销售出库单）给的值："+dispatchOrderF);
            map = kisService.insertXsckd(dispatchOrderF);
            LOGGER.info("退货通知单反馈（销售出库单）："+map);
        }
        if(map.get("MSGCODE").equals("0")){
            return AjaxResult_KIS.success("success",map.get("MSG"));
        }else {
            return AjaxResult_KIS.error("error",map.get("MSG"));
        }
    }
}
